package bean.managed;

import entity.BatchEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.BatchEntityFacade;
import bean.session.DepartmentEntityFacade;
import bean.session.PickingOrderEntityFacade;
import bean.session.ReservationEntityFacade;
import bean.session.SalesOrderEntityFacade;
import entity.CompletedGoodsLocationEntity;
import entity.DisposalEntity;
import entity.InventoryEntity;
import entity.LocationQuantityEntity;
import entity.PickListEntity;
import entity.PlannedReserveEntity;
import entity.RawMaterialPurchaseOrderEntity;
import entity.RawMaterialsLocationEntity;
import entity.ReservationEntity;
import entity.SystemUserEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import type.PickingOrderStatus;
import util.Fixtures.Department;

@ManagedBean(name = "batchEntityController")
@SessionScoped
public class BatchEntityController extends AbstractBacking implements Serializable {

    private int fulfilledCases;
    private BatchEntity current;
    private DataModel items = null;
    private DataModel CGbatchesLog = null;
    private DataModel RMbatchesLog = null;
    @EJB
    private PickingOrderEntityFacade pickingOrderEntityFacade;
    @EJB
    private SalesOrderEntityFacade salesOrderEntityFacade;
    @EJB
    private DepartmentEntityFacade departmentFacade;
    @EJB
    private bean.session.BatchEntityFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    @ManagedProperty(value = "#{inventoryEntityController}")
    InventoryEntityController inventoryEntityController;
    private CompletedGoodsLocationEntity cGLocation;
    private RawMaterialsLocationEntity rMLocation;
    private LocationQuantityEntity locationQuantityEntity;
    @ManagedProperty(value = "#{completedGoodsLocationEntityController}")
    CompletedGoodsLocationEntityController completedGoodsLocationEntityController;
    @ManagedProperty(value = "#{rawMaterialsLocationEntityController}")
    RawMaterialsLocationEntityController rawMaterialsLocationEntityController;
    @ManagedProperty(value = "#{locationQuantityEntityController}")
    LocationQuantityEntityController locationQuantityEntityController;
    @ManagedProperty(value = "#{plannedReserveEntityController}")
    PlannedReserveEntityController plannedReserveEntityController;
    @ManagedProperty(value = "#{outboundCompletedGoodsEntityController}")
    OutboundCompletedGoodsEntityController outboundCompletedGoodsEntityController;
    @ManagedProperty(value = "#{systemMessageController}")
    private SystemMessageController systemMessageController;
    @EJB
    ReservationEntityFacade reservationEntityFacade;
    @ManagedProperty(value = "#{pickListEntityController}")
    PickListEntityController pickListEntityController;
    private Date currentDate;
    private RawMaterialPurchaseOrderEntity rawMaterialPurchaseOrderEntity;
    private PlannedReserveEntity plannedReserve;
    private int amountLeftForFufilment;

    public BatchEntityController() {
    }

    public int getAmountLeftForFufilment() {
        return amountLeftForFufilment;
    }

    public void setAmountLeftForFufilment(int amountLeftForFufilment) {
        this.amountLeftForFufilment = amountLeftForFufilment;
    }

    public PickListEntityController getPickListEntityController() {
        return pickListEntityController;
    }

    public void setPickListEntityController(PickListEntityController pickListEntityController) {
        this.pickListEntityController = pickListEntityController;
    }

    public PlannedReserveEntityController getPlannedReserveEntityController() {
        return plannedReserveEntityController;
    }

    public void setPlannedReserveEntityController(PlannedReserveEntityController plannedReserveEntityController) {
        this.plannedReserveEntityController = plannedReserveEntityController;
        plannedReserveEntityController.setBatchEntityController(this);
    }

    public PlannedReserveEntity getPlannedReserve() {
        return plannedReserve;
    }

    public void setPlannedReserve(PlannedReserveEntity plannedReserve) {
        this.plannedReserve = plannedReserve;
    }

    public int getFulfilledCases() {
        return fulfilledCases;
    }

    public void setFulfilledCases(int fulfilledCases) {
        System.out.println("Setting fulfilled"+fulfilledCases);
        this.fulfilledCases = fulfilledCases;
    }

    public RawMaterialPurchaseOrderEntity getRawMaterialPurchaseOrderEntity() {
        return rawMaterialPurchaseOrderEntity;
    }

    public void setRawMaterialPurchaseOrderEntity(RawMaterialPurchaseOrderEntity rawMaterialPurchaseOrderEntity) {
        System.out.println("Setting rmPOentity" + rawMaterialPurchaseOrderEntity.getAmountLeft());
        this.rawMaterialPurchaseOrderEntity = rawMaterialPurchaseOrderEntity;
    }

    public SystemMessageController getSystemMessageController() {
        return systemMessageController;
    }

    public void setSystemMessageController(SystemMessageController systemMessageController) {
        this.systemMessageController = systemMessageController;
    }

    public Date getCurrentDate() {
        currentDate = new Date();
        return currentDate;
    }

    public OutboundCompletedGoodsEntityController getOutboundCompletedGoodsEntityController() {
        return outboundCompletedGoodsEntityController;
    }

    public void setOutboundCompletedGoodsEntityController(OutboundCompletedGoodsEntityController outboundCompletedGoodsEntityController) {
        this.outboundCompletedGoodsEntityController = outboundCompletedGoodsEntityController;
    }

    public void setCurrentDate(Date currentDate) {
        this.currentDate = currentDate;
    }

    public DataModel getRMbatchesLog() {
        RMbatchesLog = new ListDataModel(this.getFacade().findAllRMBatches());
        return RMbatchesLog;
    }

    public void setRMbatchesLog(DataModel RMbatchesLog) {
        this.RMbatchesLog = RMbatchesLog;
    }

    public DataModel getCGbatchesLog() {
        CGbatchesLog = new ListDataModel(this.getFacade().findAllCGBatches());
        return CGbatchesLog;
    }

    public void setCGbatchesLog(DataModel CGbatchesLog) {
        this.CGbatchesLog = CGbatchesLog;
    }

    public BatchEntityFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(BatchEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

    public RawMaterialsLocationEntity getrMLocation() {
        return rMLocation;
    }

    public void setrMLocation(RawMaterialsLocationEntity rMLocation) {
        this.rMLocation = rMLocation;
    }

    public RawMaterialsLocationEntityController getRawMaterialsLocationEntityController() {
        return rawMaterialsLocationEntityController;
    }

    public void setRawMaterialsLocationEntityController(RawMaterialsLocationEntityController rawMaterialsLocationEntityController) {
        this.rawMaterialsLocationEntityController = rawMaterialsLocationEntityController;
    }

    public LocationQuantityEntityController getLocationQuantityEntityController() {
        return locationQuantityEntityController;
    }

    public void setLocationQuantityEntityController(LocationQuantityEntityController locationQuantityEntityController) {
        this.locationQuantityEntityController = locationQuantityEntityController;
    }

    public CompletedGoodsLocationEntityController getCompletedGoodsLocationEntityController() {
        return completedGoodsLocationEntityController;
    }

    public void setCompletedGoodsLocationEntityController(CompletedGoodsLocationEntityController completedGoodsLocationEntityController) {
        this.completedGoodsLocationEntityController = completedGoodsLocationEntityController;
    }

    public LocationQuantityEntity getLocationQuantityEntity() {
        if (locationQuantityEntity == null) {
            locationQuantityEntity = new LocationQuantityEntity();
        }
        return locationQuantityEntity;
    }

    public void setLocationQuantityEntity(LocationQuantityEntity locationQuantityEntity) {
        this.locationQuantityEntity = locationQuantityEntity;
    }

    public CompletedGoodsLocationEntity getcGLocation() {
        return cGLocation;
    }

    public void setcGLocation(CompletedGoodsLocationEntity cGLocation) {
        this.cGLocation = cGLocation;
    }

    public InventoryEntityController getInventoryEntityController() {
        return inventoryEntityController;
    }

    public void setInventoryEntityController(InventoryEntityController inventoryEntityController) {
        this.inventoryEntityController = inventoryEntityController;
    }

    public BatchEntity getSelected() {
        if (current == null) {
            current = new BatchEntity();
            selectedItemIndex = -1;
        }
        return current;
    }

    private BatchEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareRawMaterialsLog() {
        recreateModel();
        return "/entities/rawMaterialEntity/RawMaterialsLog?faces-redirect=true";
    }

    public String prepareCompletedGoodsLog() {
        recreateModel();
        return "/entities/completedGoodsEntity/CompletedGoodsLog?faces-redirect=true";
    }

    public String prepareView() {
        current = (BatchEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new BatchEntity();
        selectedItemIndex = -1;
        return "/entities/batchEntity/Create?faces-redirect=true";
    }

    public void fulfilPlannedReservation() {
        try {
            System.out.println("Fulfilledcases=" + fulfilledCases);
            
            current.setAmountLeftForFulfilment(current.getAmountLeftForFulfilment() - fulfilledCases);
            ReservationEntity reservation = new ReservationEntity();

            reservationEntityFacade.create(reservation);
            reservation.setSalesOrder(this.plannedReserve.getSalesOrder());
            reservation.setProduct(plannedReserve.getProduct());
            plannedReserve.getProduct().getReservations().add(reservation);
            reservation.setQuantity(fulfilledCases);
            reservation.getPickingOrder().setProduct(this.plannedReserve.getProduct());
            if (this.plannedReserve.getSalesOrder().getBackorder() != null) {
                reservation.getPickingOrder().setPickDate(this.plannedReserve.getSalesOrder().getBackorder().getConfirmedLeadTime());
            } else if (this.plannedReserve.getSalesOrder().getBackorder() == null) {
                if (this.plannedReserve.getSalesOrder().getPurchaseOrder().getPreferredLeadTime() == null) {
                    reservation.getPickingOrder().setPickDate(this.plannedReserve.getSalesOrder().getPurchaseOrder().getSalesQuotation().getIndicativeLeadTime());
                    this.pickingOrderEntityFacade.scheduleTimer(this.plannedReserve.getSalesOrder().getPurchaseOrder().getSalesQuotation().getIndicativeLeadTime(), reservation.getPickingOrder().getId());

                } else {
                    reservation.getPickingOrder().setPickDate(this.plannedReserve.getSalesOrder().getPurchaseOrder().getPreferredLeadTime());
                    this.pickingOrderEntityFacade.scheduleTimer(this.plannedReserve.getSalesOrder().getPurchaseOrder().getPreferredLeadTime(), reservation.getPickingOrder().getId());
                }
            }
            this.plannedReserve.getSalesOrder().getReservations().add(plannedReserve);
            plannedReserve.getProduct().getPickingOrder().add(reservation.getPickingOrder());
            reservation.getPickingOrder().setReservation(reservation);
            reservation.setPickingOrder(reservation.getPickingOrder());
            reservation.getPickingOrder().setStatus(PickingOrderStatus.draft);

            if (plannedReserve.getSalesOrder().getPickList() == null) {
                PickListEntity pickList = new PickListEntity();
                pickList.setSalesOrder(plannedReserve.getSalesOrder());
                this.getPickListEntityController().getEjbFacade().create(pickList);
                this.plannedReserve.getSalesOrder().setPickList(pickList);
                pickList.setSalesOrder(this.plannedReserve.getSalesOrder());
            }
            reservation.getPickingOrder().setPickList(this.plannedReserve.getSalesOrder().getPickList());
//        System.out.println(currentReserve.getPickingOrder().getId());


            this.plannedReserve.getSalesOrder().getPickList().getPickingOrders().add(reservation.getPickingOrder());

            reservation.setSalesOrder(this.plannedReserve.getSalesOrder());
            reservation.getSalesOrder().getReservations().add(reservation);
            salesOrderEntityFacade.edit(reservation.getSalesOrder());

            getFacade().edit(current);
            this.getPlannedReserve().setAmountFulfilled(this.plannedReserve.getAmountFulfilled() + fulfilledCases);
            if (this.plannedReserve.getQuantity() <= this.plannedReserve.getAmountFulfilled()) {
                this.plannedReserve.setArchived(true);
            }
            this.getPlannedReserveEntityController().getEjbFacade().edit(plannedReserve);
            
            fulfilledCases = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }

        FacesContext context = FacesContext.getCurrentInstance();
        String viewId = context.getViewRoot().getViewId();
        ViewHandler handler = context.getApplication().getViewHandler();
        UIViewRoot root = handler.createView(context, viewId);
        root.setViewId(viewId);
        context.setViewRoot(root);
    }
    
     public void addLocationRM() {
        LocationQuantityEntity locationQuantityEntity = new LocationQuantityEntity();
        locationQuantityEntity.setInventory(current.getInventory());
        locationQuantityEntity.setType("RM");
        //set usage case in completedGoodsLocation
        getrMLocation().setUsageKg(getrMLocation().getUsageKg() + getrMLocation().getToAddKg());
        //set unassignedCases in completedGoodsLocation
        getSelected().setUnassignedKg(getSelected().getUnassignedKg() - getrMLocation().getToAddKg());
        //set quantity in LocationQuantityEntity
        locationQuantityEntity.setQuantity(getrMLocation().getToAddKg());
        //update currentQuantity in inventory entity
        current.getInventory().setCurrentQuantity(current.getInventory().getCurrentQuantity() + getrMLocation().getToAddKg());
        getrMLocation().setToAddKg(0);
        getFacade().edit(current);
        
        getRawMaterialsLocationEntityController().getFacade().edit(getrMLocation());
        
        locationQuantityEntity.setRawMaterialsLocation(getrMLocation());
        List<LocationQuantityEntity> locationQuantities = new ArrayList<LocationQuantityEntity>(current.getInventory().getLocationToQuantity());
        getLocationQuantityEntityController().getEjbFacade().create(locationQuantityEntity);
        current.getInventory().getLocationToQuantity().add(locationQuantityEntity);
        
        getInventoryEntityController().getEjbFacade().edit(current.getInventory());
        getRawMaterialsLocationEntityController().recreateModel();
        
        setrMLocation(null);


        //to refresh page
        FacesContext context = FacesContext.getCurrentInstance();
        String viewId = context.getViewRoot().getViewId();
        ViewHandler handler = context.getApplication().getViewHandler();
        UIViewRoot root = handler.createView(context, viewId);
        root.setViewId(viewId);
        context.setViewRoot(root);

        //getFacade().edit(current);
    }
    
//     public void addLocationRM() {
//             LocationQuantityEntity locationQuantityEntity = new LocationQuantityEntity();
//             getLocationQuantityEntityController().getEjbFacade().create(locationQuantityEntity);
//        locationQuantityEntity.setInventory(current.getInventory());
//        //set usage case in completedGoodsLocation
//        getrMLocation().setUsageKg(getrMLocation().getUsageKg() + getrMLocation().getToAddKg());
//        //set unassignedCases in completedGoodsLocation
//        getSelected().setUnassignedKg(getSelected().getUnassignedKg() - getrMLocation().getToAddKg());
//        //set quantity in LocationQuantityEntity
//        locationQuantityEntity.setQuantity(getrMLocation().getToAddKg());
//        //update currentQuantity in inventory entity
//        current.getInventory().setCurrentQuantity(current.getInventory().getCurrentQuantity() + getrMLocation().getToAddKg());
//        getrMLocation().setToAddKg(0);
//        getFacade().edit(current);
//
//        //changed here
//        getRawMaterialsLocationEntityController().getFacade().edit(getrMLocation());
//         
//               
//
//        List<LocationQuantityEntity> locationQuantities = new ArrayList<LocationQuantityEntity>(current.getInventory().getLocationToQuantity());
//        
//        current.getInventory().getLocationToQuantity().add(locationQuantityEntity);
//
//        getInventoryEntityController().getEjbFacade().edit(current.getInventory());
//locationQuantityEntity.setLocation(getrMLocation());
//        
//        getrMLocation().getLocationToQuantity().add(locationQuantityEntity);
//        getRawMaterialsLocationEntityController().getFacade().edit(getrMLocation());
//
//        getLocationQuantityEntityController().getEjbFacade().edit(locationQuantityEntity);
//        getRawMaterialsLocationEntityController().recreateModel();
//
//        setrMLocation(null);
//
//        //to refresh page
//        FacesContext context = FacesContext.getCurrentInstance();
//        String viewId = context.getViewRoot().getViewId();
//        ViewHandler handler = context.getApplication().getViewHandler();
//        UIViewRoot root = handler.createView(context, viewId);
//        root.setViewId(viewId);
//        context.setViewRoot(root);
//
//        //getFacade().edit(current);
//    }

    public void addLocation() {
        LocationQuantityEntity locationQuantityEntity = new LocationQuantityEntity();
        locationQuantityEntity.setInventory(current.getInventory());
        locationQuantityEntity.setType("CG");
        //set usage case in completedGoodsLocation
        getcGLocation().setUsageCase(getcGLocation().getUsageCase() + getcGLocation().getToAddCase());
        //set unassignedCases in completedGoodsLocation
        getSelected().setUnassignedCases(getSelected().getUnassignedCases() - getcGLocation().getToAddCase());
        //set quantity in LocationQuantityEntity
        locationQuantityEntity.setQuantity(getcGLocation().getToAddCase());
        //update currentQuantity in inventory entity
        current.getInventory().setCurrentQuantity(current.getInventory().getCurrentQuantity() + getcGLocation().getToAddCase());
        getcGLocation().setToAddCase(0);
        getFacade().edit(current);

        getCompletedGoodsLocationEntityController().getFacade().edit(getcGLocation());

        locationQuantityEntity.setLocation(getcGLocation());

        List<LocationQuantityEntity> locationQuantities = new ArrayList<LocationQuantityEntity>(current.getInventory().getLocationToQuantity());
        getLocationQuantityEntityController().getEjbFacade().create(locationQuantityEntity);
        current.getInventory().getLocationToQuantity().add(locationQuantityEntity);

        getInventoryEntityController().getEjbFacade().edit(current.getInventory());

        getcGLocation().getLocationToQuantity().add(locationQuantityEntity);
        getCompletedGoodsLocationEntityController().getFacade().edit(getcGLocation());

        getCompletedGoodsLocationEntityController().recreateModel();

        setcGLocation(null);


        //to refresh page
        FacesContext context = FacesContext.getCurrentInstance();
        String viewId = context.getViewRoot().getViewId();
        ViewHandler handler = context.getApplication().getViewHandler();
        UIViewRoot root = handler.createView(context, viewId);
        root.setViewId(viewId);
        context.setViewRoot(root);

        //getFacade().edit(current);
    }

    public String createRM() {
        try {
            System.out.println("HEREEE dieeeee first");
            DisposalEntity disposalEntity = new DisposalEntity();
            disposalEntity.setQuantity(0);
            disposalEntity.setCreatedBy(getLoginPerson());
            current.setDisposal(disposalEntity);
            current.setCreatedBy(getLoginPerson());
            disposalEntity.setBatch(current);
            current.setDateEntered(new Date());
            current.setType("RM");
            InventoryEntity inventoryEntity = new InventoryEntity();
            //inventoryEntity.setCurrentQuantity(current.getQuantity());
            current.setUnassignedKg(current.getQuantity());
            //inventoryEntity.setLocationToQuantity(null);

//            Date currentDate = new Date();
//            SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
//            sdfDate.format(currentDate);
//            Calendar c = Calendar.getInstance();
//            c.setTime(currentDate);
//            c.add(Calendar.DATE, 120);  // number of days to add
//            current.setExpiryDate(c.getTime());

            current.setInventory(inventoryEntity);
            inventoryEntity.setBatch(current);
            getFacade().create(current);

            SystemUserEntity purchasingManager = departmentFacade.findDepartmentByName(Department.Purchasing.getName()).getManager();
            systemMessageController.getEjbFacade().createAndSendSystemMessage(purchasingManager,
                    current.getQuantity() + " " + current.getProduct().getProductName() + " for purchase order #" + this.getRawMaterialPurchaseOrderEntity().getId() + " has been received.",
                    "/entities/purchasing/AcknowledgeOrder.xhtml", systemMessageController);

            getRawMaterialsLocationEntityController().recreateModel();
            recreateModel();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("BatchEntityCreated"));
            return "/entities/inventoryEntity/CreateRM?faces-redirect=true";
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String createCG() {
        try {
            DisposalEntity disposalEntity = new DisposalEntity();
            disposalEntity.setQuantity(0);
            disposalEntity.setCreatedBy(getLoginPerson());
            current.setDisposal(disposalEntity);
            current.setCreatedBy(getLoginPerson());
            current.setArchived(false);
            current.setDateEntered(new Date());
            current.setType("CG");
            disposalEntity.setBatch(current);
            InventoryEntity inventoryEntity = new InventoryEntity();
            //inventoryEntity.setCurrentQuantity(current.getQuantity());
            current.setUnassignedCases(current.getQuantity());
            current.setAmountLeftForFulfilment(current.getQuantity());
            //inventoryEntity.setLocationToQuantity(null);

            //To automatically set expiry date
//            Date currentDate = new Date();
//            SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
//            sdfDate.format(currentDate);
//            Calendar c = Calendar.getInstance();
//            c.setTime(currentDate);
//            c.add(Calendar.DATE, 120);  // number of days to add
//            current.setExpiryDate(c.getTime());

            //inventoryEntity.setCurrentQuantity(current.getQuantity());
            current.setInventory(inventoryEntity);
            inventoryEntity.setBatch(current);
            getFacade().create(current);
            getCompletedGoodsLocationEntityController().recreateModel();
            recreateModel();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("BatchEntityCreated"));
            return "/entities/inventoryEntity/CreateCG?faces-redirect=true";
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String createCGRedirectToPlannedReserve() {
        try {
            DisposalEntity disposalEntity = new DisposalEntity();
            disposalEntity.setQuantity(0);
            disposalEntity.setCreatedBy(getLoginPerson());
            
            this.getSelected().setDisposal(disposalEntity);
            this.getSelected().setCreatedBy(getLoginPerson());
            this.getSelected().setArchived(false);
            this.getSelected().setDateEntered(new Date());
           this.getSelected().setType("CG");
            disposalEntity.setBatch(this.getSelected());
            InventoryEntity inventoryEntity = new InventoryEntity();
            //inventoryEntity.setCurrentQuantity(current.getQuantity());
            this.getSelected().setUnassignedCases(this.getSelected().getQuantity());
            this.getSelected().setAmountLeftForFulfilment(this.getSelected().getQuantity());
            //inventoryEntity.setLocationToQuantity(null);

            //To automatically set expiry date
//            Date currentDate = new Date();
//            SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
//            sdfDate.format(currentDate);
//            Calendar c = Calendar.getInstance();
//            c.setTime(currentDate);
//            c.add(Calendar.DATE, 120);  // number of days to add
//            current.setExpiryDate(c.getTime());

            this.getSelected().setInventory(inventoryEntity);
            inventoryEntity.setBatch(this.getSelected());
            getFacade().create(this.getSelected());
            getCompletedGoodsLocationEntityController().recreateModel();
            recreateModel();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("BatchEntityCreated"));
            return "/entities/plannedReserveEntity/List?faces-redirect=true";
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

   

    public String prepareEdit() {
        current = (BatchEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("BatchEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (BatchEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("BatchEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        this.getOutboundCompletedGoodsEntityController().recreateModel();
        this.CGbatchesLog = null;
        this.RMbatchesLog = null;
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = BatchEntity.class)
    public static class BatchEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            BatchEntityController controller = (BatchEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "batchEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof BatchEntity) {
                BatchEntity o = (BatchEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + BatchEntityController.class.getName());
            }
        }
    }
}
